package comm;

import java.io.DataInputStream;
import java.io.IOException;
import java.util.Arrays;

public class ClientInputListener implements Runnable {
	private DataInputStream in;
	
	private boolean ready;
	private int input;
	
	private Client client;
	
	public ClientInputListener(DataInputStream in, Client client) {
		this.in = in;
		this.client = client;
		input = -1;
	}
	
	@Override
	public void run() {
		for(;;) {
			if(client.isIdentified()) {
				if(!ready) {
					try {
						input = in.readInt();
					} catch (IOException e) {
						e.printStackTrace();
						return;
					}
					
					if(input != -1) {
						ready = true;
					}
				}
			} else {
				String tmp = "";
				try {
					tmp = in.readUTF();
				} catch (IOException e) {
					e.printStackTrace();
					return;
				}
				
				if(tmp != "") {
					String[] tmp2 = tmp.split("\\^");
					
					System.out.println(Arrays.toString(tmp2));
					
					if(tmp2.length != 2) {
						System.out.println("Error: Client refused to identify.");
						try {
							client.socket.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					
					client.preferredName = tmp2[0];
					client.preferredColor = Integer.parseInt(tmp2[1]);
					client.setIdentified(true);
				}
			}
			
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	public boolean isReady() {
		return ready;
	}

	public int getInput() {
		int out = input;
		input = -1;
		ready = false;
		return out;
	}
}